package com.weishenai.customerassistant.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weishenai.customerassistant.common.Result;
import com.weishenai.customerassistant.entity.Electrical;
import com.weishenai.customerassistant.service.ElectricalService;
import com.weishenai.customerassistant.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.List;

@Slf4j
@Api(tags = "管理系统_配变信息管理")
@RestController
@RequestMapping("/area")
public class ElectricalController extends BaseController {
    @Autowired
    private ElectricalService electricalService;

    /**
     * excel文件存放的目录
     */
    @Value("${file.excelDir}")
    private String excelDir;

    @PreAuthorize("hasAuthority('distribution:list:add')")
    @PostMapping("/inset")
    @ApiOperation("增加一条配变信息")
    public Object insetElectrical(@RequestBody Electrical area) {
        Integer result = electricalService.insertElectrical(area);
        return result > 0 ? Result.success() : Result.failed("失败");
    }

//    @ApiOperation("小程序_根据输入的供电变压器部分名称查询配变信息")
//    @ApiImplicitParam(name = "name", value = "配变名字")
//    @GetMapping("/selectByName/{name}")
//    public Object selectByName(@PathVariable("name") String name) {
//        List<Electrical> list = electricalService.selectByName(name);
//        return Result.success(list);
//    }

    @PreAuthorize("hasAuthority('distribution:list:delete')")
    @PostMapping("/del/{id}")
    @ApiOperation("根据ID删除一条配变信息")
    @ApiImplicitParam(name = "id", value = "配变信息的id")
    public Object delElectrical(@PathVariable("id") Integer areaId) {
        log.info("删除配变信息的id：" + areaId);
        Integer result = electricalService.delElectrical(areaId);
        return result > 0 ? Result.success() : Result.failed("失败");
    }

    @PreAuthorize("hasAuthority('distribution:list:edit')")
    @PostMapping("/update")
    @ApiOperation("修改一条配变信息")
    public Object updateElectrical(@RequestBody Electrical electrical) {
        electrical.setCreatedTime(DateUtils.getTime());
        Integer result = electricalService.updateElectrical(electrical);
        return result > 0 ? Result.success() : Result.failed("失败");
    }

    @PreAuthorize("hasAuthority('distribution:list')")
    @PostMapping("/select/{pageNum}/{pageSize}/{keyword}")
    @ApiOperation("查询所有的配变数据（有关键字）")
    public Object updateElectrical(@PathVariable(name = "pageNum") Integer pageNum, @PathVariable(name = "pageSize") Integer pageSize, @PathVariable("keyword") String keyword) {
        IPage<Electrical> iPage = electricalService.getElectrical(pageNum, pageSize, keyword);
        return iPage.getRecords() != null ? Result.success(iPage) : Result.failed("失败");
    }

    @PreAuthorize("hasAuthority('distribution:list')")
    @ApiOperation("查询所有的配变数据（没有关键字）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "第几页"),
            @ApiImplicitParam(name = "pageSize", value = "每一页的数量"),
    })
    @GetMapping("/selectAll/{pageNum}/{pageSize}")
    public Object selectAll(@PathVariable(name = "pageNum") Integer pageNum, @PathVariable(name = "pageSize") Integer pageSize) {
        IPage<Electrical> iPage = electricalService.getElectrical(pageNum, pageSize, null);
        return iPage.getRecords() != null ? Result.success(iPage) : Result.failed("失败");
    }

    @ApiOperation("一键把Excel数据导入数据库")
//    @ApiImplicitParam(name = "multipartFile", value = "上传文件")
    @GetMapping("/Excel2DB")
//    public Object Excel2DB(@RequestParam(value = "file") MultipartFile multipartFile) {
    public Object Excel2DB() {
        try {
//            if (multipartFile == null) return Result.fail("失败,文件为空");
            File file = new File(excelDir);
            file.mkdir();
//            multipartFile.transferTo(file);
            ExcelReader reader = ExcelUtil.getReader(excelDir);
            List<Electrical> all = reader.readAll(Electrical.class);
            log.info("从Excel读取数据成功，共" + all.size() + "条数据");
            for (int i = 0; i < all.size(); i++) {
                if (all.get(i).getId() != null) {
                    log.info("正在导入第" + i + "条数据");
                    electricalService.Excel2DB(all.get(i));
                } else return Result.failed("excel的id号码不能为空");
            }
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("失败" + e.getMessage());
        }
    }


}
